<template>
  <div class="dialog-wrapper">
    <el-dialog
      :visible.sync="chooseVisible"
      title="选择产品"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
    >
      <el-card shadow="never" class="aui-card--fill managementWrapper">
        <div class="mod-sys__user">
          <el-form
            :inline="true"
            :model="dataForm"
            @keyup.enter.native="getDataList()"
          >
            <el-form-item>
              <el-input
                v-model="dataForm.name"
                placeholder="产品名称"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button @click="getDataList()">搜索</el-button>
            </el-form-item>
          </el-form>
          <el-table
            ref="orderMultipleTable"
            :data="transProductList"
            @select="onSelect"
            style="width: 100%"
            border
          >
            <el-table-column type="selection" width="40"> </el-table-column>
            <el-table-column
              type="index"
              label="序号"
              header-align="center"
              align="center"
              width="80"
            ></el-table-column>
            <el-table-column label="产品" header-align="center" align="center">
              <template slot-scope="scope">
                <div class="disCenter itemBox">
                  <div class="imgBox">
                    <img :src="scope.row.product_master_pic" />
                  </div>
                  <div class="rightBox">
                    <el-tooltip
                      class="item"
                      effect="light"
                      :content="scope.row.name"
                      placement="top"
                    >
                      <span class="top overTwoHidden">{{
                        scope.row.name
                      }}</span>
                    </el-tooltip>

                    <span class="bottom"
                      >产品编号: {{ scope.row.product_serial }}</span
                    >
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="remarks"
              label="备注"
              width="270"
              header-align="center"
              align="center"
            >
              <template slot-scope="scope">
                <div class="overTwoHidden" style="max-width: 260px">
                  {{ scope.row.remarks }}
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
      <template slot="footer">
        <el-button @click="handleCancel">{{ $t("cancel") }}</el-button>
        <el-button type="primary" @click="handleCheck">{{
          $t("confirm")
        }}</el-button>
      </template>
      <SkuChoose
        v-if="dialogVisible"
        ref="productSku"
        @handleClose="skuClose"
        @handleConfirm="skuConfirm"
        :skuList="skuArr"
      ></SkuChoose>
    </el-dialog>
  </div>
</template>

<script>
import _ from "lodash";
import SkuChoose from "@/components/sku-choose";
export default {
  props: {
    chooseData: {
      type: Array,
    },
    orderProductData: {
      type: Array,
    },
  },
  components: {
    SkuChoose,
  },
  data() {
    return {
      chooseVisible: true,
      chooseInfo: [],
      chooseProductInfo: {},
      skuArr: [],
      dialogVisible: false,
      chooseProductListObj: {},
      transProductList: [],
      oldTransProductList: [],
      dataForm: {
        name: "",
      },
    };
  },
  watch: {
    orderProductData: {
      handler(val, oldVal) {
        console.log(val);
        this.transProduct();
      },
      immediate: true,
    },
  },
  //   [
  //   {
  //     "id": 2,
  //     "order_id": 1,
  //     "product_id": 3,
  //     "product_sku_id": 20,
  //     "sale_price": "115.00",
  //     "sale_num": 1,
  //     "total_price": "115.00",
  //     "delivery_date": "2023-03-25",
  //     "remarks": "无无",
  //     "product_serial": "CP2023032513392476718593",
  //     "product_name": "修正版-罗技（G）G PRO 游戏机械键盘 有线键盘 87键紧凑设计 RGB多彩炫光 GPRO机械键盘 C轴 类青轴",
  //     "product_master_pic": "http://webman.hujiaze.top/public/upload/2023-03-22/8965d97d1a80dc93c6add106f90ab039.png",
  //     "surplus_production_total": 1,
  //     "sku_name": "白色+M"
  //   },
  // ]
  methods: {
    getDataList() {
      console.log(this.dataForm.name);
      const name = this.dataForm.name;
      const list = this.oldTransProductList.filter(
        (item) => item.name.indexOf(name) > -1
      );
      this.transProductList = list;
    },
    getCurrentCheckSkuList(row) {
      const list = _.cloneDeep(this.chooseData);
      // debugger
      const fitProductList = list.filter((item) => item.product_id === row.id);
      let tempSkuList = [];
      if (fitProductList.length > 0) {
        let arr = _.cloneDeep(row.sku_list)
        let temp = [];
        fitProductList.forEach((item) => {
          temp = arr.filter((it) => it.id !== item.product_sku_id);
          arr = [...temp];
        });
        tempSkuList = temp;
      } else {
        tempSkuList = row.sku_list;
      }
      return tempSkuList;
    },
    onSelect(rows, row) {
      let selected = rows.length && rows.indexOf(row) !== -1;
      console.log(selected); // true就是选中，0或者false是取消选中
      if (selected) {
        this.chooseProductInfo = row;
        const list = this.getCurrentCheckSkuList(row);
        if (list.length > 0) {
          
          this.skuArr = list.filter((item) => item.bom_id !== 0);
          if(this.skuArr.length > 0) {
            this.dialogVisible = true;
          } else {
            this.$message.warning("当前产品未绑定BOM相关信息，无法进行选择操作！");
            this.$refs.orderMultipleTable.toggleRowSelection(row)
          }
        } else {
          this.$message.warning("当前产品暂无可添加SKU数据，请添加后操作！");
          this.$refs.orderMultipleTable.toggleRowSelection(row);
        }
      } else {
        const key = row.id;
        this.chooseProductListObj[key] = [];
      }
    },
    transProduct() {
      console.log(this.orderProductData);
      let arr = [];
      this.orderProductData.forEach((item) => {
        arr.push(item.product_id);
      });
      const unique = [...new Set(arr)];
      let prodList = [];
      unique.forEach((item) => {
        let obj = this.orderProductData.find((it) => it.product_id === item);
        const {
          product_id,
          product_master_pic,
          product_name,
          product_serial,
          remarks,
        } = obj;
        const params = {
          id: product_id,
          product_master_pic,
          name: product_name,
          product_serial,
          remarks,
          sku_list: [],
        };
        prodList.push(params);
      });
      // // transProductList

      for (let i = 0; i < prodList.length; i++) {
        for (let j = 0; j < this.orderProductData.length; j++) {
          const it = this.orderProductData[j];
          if (prodList[i].id === it.product_id) {
            prodList[i].sku_list.push({
              id: it.product_sku_id,
              product_id: prodList[i].id,
              sku_name: it.sku_name,
              sale_price: it.sale_price,
              min_stock: it.surplus_production_total,
              delivery_date: it.delivery_date,
              sale_num: it.sale_num,
              bom_id: it.bom_id,
            });
          }
        }
      }
      this.transProductList = prodList;
      this.oldTransProductList = prodList;
      console.log(prodList);
    },
    skuConfirm(row) {
      console.log(row);
      console.log(row);
      const arr = [];
      row.forEach((item) => {
        const {
          id,
          product_id,
          product_sku_id,
          sku_name,
          bom_id,
          sale_num,
          delivery_date,
        } = item;
        const { name, product_serial, product_master_pic } = this.chooseProductInfo;
        
        const temp = {
          // 子订单id
          id: 0,
          product_id,
          product_sku_id,
          sku_name,
          price: null,
          sale_num,
          delivery_date,
          product_name: name,
          product_serial,
          // 写死，后续更换
          bom_id,
          product_master_pic,
        };
        arr.push(temp);
      });
      const key = this.chooseProductInfo.id;
      this.chooseProductListObj[key] = arr;
      console.log(this.chooseProductListObj);
      // this.callbackList = arr;
    },
    skuClose() {
      this.dialogVisible = false;
    },
    handleCheck() {
      // if (this.chooseInfo.length < 1) {
      //   this.$message.warning("请选择产品");
      //   return;
      // }
      // this.chooseInfo.forEach((item) => {
      //   item.product_sku_id = item.id;
      // });
      let arr = [];
      for (let key in this.chooseProductListObj) {
        arr = [...arr, ...this.chooseProductListObj[key]];
      }

      console.log(arr);
      if (arr.length < 1) {
        this.$message.warning("请选择产品对应SKU数据！");
        return;
      }
      this.$emit("orderProductConfirm", arr);

      this.$emit("orderProductClose");
    },
    handleCancel() {
      this.$emit("orderProductClose");
    },
  },
};
</script>

<style lang="scss" scoped>
.dialog-wrapper {
  ::v-deep .el-dialog {
    width: 50% !important;
  }
  .managementWrapper {
    .prodBox {
      padding-left: 6px;
      .imgBox {
        width: 64px;
        height: 64px;
        img {
          width: 100%;
          height: 100%;
        }
      }
      .rightBox {
        margin-left: 14px;
        text-align: left;
        .top {
          max-width: 200px;
          margin-bottom: 6px;
        }
        .bottom {
          color: $mainColor;
        }
      }
    }
  }
}
</style>

<style lang="scss">
::v-deep .el-dialog__footer {
  border-top: 1px solid #f4f4f4 !important;
  padding: 16px 20px 16px !important;
}
</style>
